<template>
  <div>
    <beetles-search :size="'mini'" @search="searchForm" @reset="emptyForm">
      <template slot-scope="{ searchConceal }" slot="searchForm">
        <el-form
          ref="form"
          :model="query"
          :rules="rules"
          label-width="100px"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item
            class="beetles-search-item"
            label="账户名称"
            prop="name"
          >
            <el-input
              id="id-business-account-queryForm-name"
              placeholder="请输入账户名"
              v-model="queryForm.name"
              clearable
              size="mini"
              @keyup.enter.native="searchForm"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="账户ID"
            prop="platformId"
          >
            <el-input
              id="id-business-account-queryForm-platformId"
              placeholder="请输入账户ID"
              v-model="queryForm.platformId"
              clearable
              size="mini"
              style=""
              @keyup.enter.native="searchForm"
            >
            </el-input>
          </el-form-item>

          <!--          <el-form-item class="beetles-search-item" label="订单名" prop="name">-->
          <!--            <el-input-->
          <!--              id="id-business-account-queryForm-offerName"-->
          <!--              placeholder="请输入订单名"-->
          <!--              v-model="queryForm.offerName"-->
          <!--              clearable-->
          <!--              size="mini"-->
          <!--              style="" @keyup.enter.native="searchForm">-->
          <!--            </el-input>-->
          <!--          </el-form-item>-->
          <el-form-item label="订单名称: " prop="offerId">
            <el-select
              id="id-business-account-queryForm-offerName"
              size="mini"
              style="width: 190px"
              v-model="queryForm.offerId"
              placeholder="请选择订单"
              clearable
              filterable
              :filter-method="costomFilterMethod"
              @visible-change="clearOfferSelect"
            >
              <el-option
                v-for="item in filterOfferList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item class="beetles-search-item" label="类型" prop="type">
            <el-select
              id="id-business-account-queryForm-type"
              v-model="queryForm.type"
              clearable
              size="mini"
              placeholder="请选择类型"
              style=""
              ref="accountType"
              @visible-change="isShowSelectOptions"
            >
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="媒体"
            prop="platform"
          >
            <el-select
              id="id-business-account-queryForm-platform"
              v-model="queryForm.platform"
              multiple
              clearable
              size="mini"
              placeholder="请选择广告媒体"
              ref="accountPlatform"
              @visible-change="isShowSelectOptions"
            >
              <el-option
                v-for="item in advPlatform"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="beetles-search-item"
            label="客户"
            prop="customerName"
          >
            <el-input
              id="id-business-account-queryForm-customerName"
              placeholder="请输入客户"
              v-model="queryForm.customerName"
              clearable
              size="mini"
              @keyup.enter.native="searchForm"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="代理"
            prop="agencyName"
          >
            <!--<el-input-->
            <!--  id="id-business-account-queryForm-agencyName"-->
            <!--  placeholder="请输入代理"-->
            <!--  v-model="queryForm.agencyName"-->
            <!--  clearable-->
            <!--  size="mini"-->
            <!--  @keyup.enter.native="searchForm">-->
            <!--</el-input>-->
            <el-select
              v-model="queryForm.agencyName"
              multiple
              clearable
              size="mini"
              placeholder="请选择代理"
            >
              <el-option
                v-for="item in agencyNameList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            class="beetles-search-item"
            label="运营人"
            prop="operator"
          >
            <el-select
              id="id-business-account-queryForm-operator"
              v-model="queryForm.operator"
              clearable
              filterable
              size="mini"
              placeholder="请选择运营人"
            >
              <el-option
                v-for="item in allUserList"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="绑定人"
            prop="binder"
          >
            <el-select
              id="id-business-account-queryForm-binder"
              v-model="queryForm.binder"
              clearable
              filterable
              size="mini"
              placeholder="请选择绑定人"
            >
              <el-option
                v-for="item in allUserList"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="绑定日期"
            prop="bindTime"
          >
            <el-date-picker
              v-model="queryForm.bindTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <!-- 后四列表 -->
          <el-form-item
            class="beetles-search-item"
            label="系统状态"
            prop="subStatus"
          >
            <el-select
              v-model="queryForm.subStatus"
              clearable
              filterable
              size="mini"
              placeholder="请选择系统状态"
            >
              <el-option
                v-for="item in systemStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="启用日期"
            prop="enableTime"
          >
            <el-date-picker
              v-model="queryForm.enableTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="0消耗日期"
            prop="pauseTime"
          >
            <el-date-picker
              v-model="queryForm.pauseTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            class="beetles-search-item"
            label="封号日期"
            prop="closeTime"
          >
            <el-date-picker
              v-model="queryForm.closeTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </template>
    </beetles-search>

    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :view-name="'account'"
        :page.sync="page"
        :permission="permissionList"
        :row-class-name-rollback="getRowClassName"
        :row-class-name="getRowClass"
        @sort-change="handleSortChange"
        v-model="form"
        ref="crud"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad(page)"
      >
        <!--      表头文字超出后省略号代替-->
        <template slot="typeHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="nameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="platformIdHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="offerIdHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="platformHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="agencyNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="bindStatusHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="offerNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="customerNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="agencyNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="ownerNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="operatorNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="bindTimeHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="statusHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot="binderNameHeader" slot-scope="{ column }">
          <div class="hanDer">{{ (column || {}).label }}</div>
        </template>
        <template slot-scope="scope" slot="menuRight">
          <el-tooltip effect="dark" content="导出账户数据" placement="top">
            <el-button
              icon="el-icon-download"
              circle
              size="small"
              @click="handleExport"
            ></el-button>
          </el-tooltip>
        </template>
        <!-- 系统状态 -->
        <template slot="subStatus" slot-scope="scope">
          <el-tag v-if="scope.row.subStatus === 0">待启用</el-tag>
          <el-tag v-if="scope.row.subStatus === 1" type="success">启用</el-tag>
          <el-tag v-if="scope.row.subStatus === 2" type="info">0消耗</el-tag>
          <el-tag v-if="scope.row.subStatus === 3" type="warning"
          >封号(待申诉）
          </el-tag
          >
          <el-tag v-if="scope.row.subStatus === 4" type="danger"
          >封号
          </el-tag
          >
        </template>
        <template slot="pullStatusHeader" slot-scope="{ column }">
          <el-popover placement="top-start" width="200" trigger="hover">
            <div class="popover_pane">
              <div>
                <i class="el-icon-info" style="color: #00a2ff"></i>
                <strong> 状态</strong>
              </div>
              <span>有效: 媒体上可正常投放</span>
              <span>无效: 媒体上不可投放</span>
              <span>未更新: 未达到系统数据更新时间</span>
            </div>
            <span slot="reference" class="text-link">{{
                (column || {}).label
              }}</span>
          </el-popover>
        </template>

        <template slot="limitsHeader" slot-scope="{ column }">
          <el-popover placement="bottom-start" width="200" trigger="hover">
            <div class="popover_pane">
              <div>
                <i class="el-icon-info" style="color: #00a2ff"></i>
                <strong> 账户余额</strong>
              </div>
              <span>
                  账户余额非实时更新，每日8:30、13:30、18:30更新<br/>
                  为方便计算，beetles系统将账户余额统一换算美元显示
                </span>
            </div>
            <span slot="reference" class="text-link">{{
                (column || {}).label
              }}</span>
          </el-popover>
        </template>

        <template slot-scope="{ row }" slot="name">
          <el-tooltip
            content="待关联订单"
            placement="top"
            v-if="row.offerName === '' && showOfferName"
          ><i class="el-icon-warning" style="color: red"></i
          ></el-tooltip>
          <div :style="row.customerName ? defaultStyle : accountNameStyle">
            {{ row.name }}
          </div>
        </template>

        <template slot-scope="{ row }" slot="limits">
          {{ thousandSeparator(row) }}
        </template>

        <template slot="operatorName" slot-scope="{ row, index }">
            <span v-if="userInfo.is_agency === 1 && row.originTenantId">
              <el-select
                id="id-business-account-operatorId"
                size="mini"
                v-model="row.operator"
                placeholder="请选择"
                @change="handleChangeOperator(row.id, row.operator)"
              >
                <el-option
                  v-for="item in innerUserList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </span>
          <span v-else>{{ row.operatorName }}</span>
        </template>

        <template slot="menuLeft">
          <div class="beetles_table_left">
            <el-button
              id="id-business-account-handleAdd"
              type="primary"
              size="small"
              icon="el-icon-plus"
              v-if="permission.account_add"
              @click="handleAddNew"
            >新增账户
            </el-button>
            <el-button
              id="id-business-account-handleDelete"
              type="danger"
              size="small"
              icon="el-icon-delete"
              v-if="permission.account_delete"
              @click="handleDelete"
            >删除账户
            </el-button>
            <!--        <el-button size="small" @click="facebookVisible = true">-->
            <!--          新增-->
            <!--        </el-button>-->
            <el-button
              id="id-business-account-batchUpdateTimezone"
              type="success"
              size="small"
              v-if="permission.account_edit"
              @click="batchUpdateTimezone"
            >
              批量修改时区
            </el-button>
            <el-button
              id="id-business-account-batchUpdateStatus"
              type="warning"
              size="small"
              v-if="permission.account_edit"
              @click="batchUpdateStatus"
            >
              批量重启
            </el-button>

            <facebook-login
              v-if="permission.account_add"
              id="id-business-account-facebook"
              ref="facebook"
              class="facebook-login"
              :appId="facebookParams.appId"
              :version="facebookParams.version"
              loginLabel="登录 Facebook "
              logoutLabel="登出 Facebook"
              :loginOptions="facebookParams.loginOptions"
              @login="onLogin"
              @logout="onLogout"
              @sdk-loaded="sdkLoaded"
              @getAdsAccount="getFbAccounts"
            >
            </facebook-login>

            <google-login
              v-if="permission.account_add && googleParams.enable"
              ref="google"
              id="id-business-account-google"
              class="google-login"
              @status="googleChangeStatus"
              :params="googleParams"
              :getGoogleAccounts="getGoogleAccounts"
            >
            </google-login>

            <el-button
              v-if="facebookParams.isConnected"
              type="primary"
              size="small"
              @click="getFbAccounts"
              :loading="facebookParams.loading"
            >
              获取广告账户
            </el-button>

            <el-button
              v-if="googleParams.isLogin"
              type="success"
              size="small"
              @click="getGoogleAccounts"
            >
              获取广告账户
            </el-button>
          </div>
        </template>
        <template slot-scope="{ row }" slot="menu">
          <el-tooltip content="查看" placement="top">
            <el-button
              id="id-business-account-rowView"
              size="small"
              icon="el-icon-view"
              type="text"
              @click="rowView(row)"
            ></el-button>
          </el-tooltip>
          <span style="padding-left: 10px"></span>
          <el-tooltip content="编辑" placement="top">
            <el-button
              id="id-business-account-rowEdit"
              icon="el-icon-edit"
              type="text"
              @click="rowEdit(row)"
              :disabled="!permissionList('editBtn', row)"
            ></el-button>
          </el-tooltip>
          <span style="padding-left: 10px"></span>
          <el-tooltip content="删除" placement="top">
            <el-button
              id="id-business-account-rowDel"
              icon="el-icon-delete"
              type="text"
              @click="rowDel(row)"
              :disabled="!permissionList('delBtn', row)"
            ></el-button>
          </el-tooltip>
        </template>

        <template slot="type" slot-scope="{ row }">
          {{
            row.originTenantId != null && row.originTenantId != ""
              ? "外部"
              : "内部"
          }}
        </template>
        <template slot="offerIdForm" slot-scope="{ row }">
          <el-select
            id="id-business-account-queryPlatformByOffer"
            v-model="row.offerId"
            @change="queryPlatformByOffer(row)"
            placeholder="请选择 订单"
            filterable="true"
          >
            <el-option
              v-for="(item, index) in offerList"
              :key="index"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </template>
        <template slot="platformForm" slot-scope="{ row }">
          <el-select
            id="id-business-account-row-platform"
            v-model="row.platform"
            :loading="platformLoading"
            placeholder="请选择订单"
          >
            <el-option
              v-for="(item, index) in platformList"
              :key="index"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </template>
        <template slot-scope="{ row }" slot="accountListForm">
          <div style="width: 200%; margin-left: -50px">
            <el-row v-for="(accountItem, idx) in row.accountList" :key="idx">
              <el-col span="6" style="min-width: 240px">
                <div class="text" style="padding-right: 10px">账户名:</div>
                <el-input
                  id="id-business-account-accountItem-name"
                  placeholder="请输入账户名"
                  v-model="accountItem.name"
                  clearable
                  size="mini"
                  style="width: 400px"
                >
                </el-input>
              </el-col>
              <el-col span="6" style="min-width: 240px">
                <div class="text" style="padding-right: 10px">账户ID:</div>
                <el-input
                  id="id-business-account-accountItem-platformId"
                  placeholder="请输入账户ID"
                  v-model="accountItem.platformId"
                  clearable
                  size="mini"
                  style="width: 400px"
                >
                </el-input>
              </el-col>
              <el-col span="2" style="min-width: 50px">
                <i
                  v-if="row.accountList != null && row.accountList.length > 1"
                  class="el-icon-delete"
                  @click="deductAccount(row, idx)"
                ></i>
              </el-col>
            </el-row>
            <el-button
              id="id-business-account-appendAccount"
              type="primary"
              icon="el-icon-add"
              size="small"
              @click="appendAccount(row)"
            >增加账户
            </el-button>
          </div>
        </template>
        <template slot-scope="{ row }" slot="platform">
          <div style="display: flex; flex-wrap: wrap">
            <div
              style="width: 20px; margin-right: 4px"
              v-for="item in platformLogo(row.platform)"
            >
              <img style="width: 100%" :src="item.url" :title="item.name"/>
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="status">
          <span v-if="row.status==0">开启</span>
          <span v-if="row.status==1">暂停</span>
          <span v-if="row.status==2">关闭</span>
          <!--            <div>-->
          <!--              <el-select-->
          <!--                v-model="row.status"-->
          <!--                @change="changeStatus($event, row)"-->
          <!--                size="mini"-->
          <!--                :disabled="true"-->
          <!--              >-->
          <!--&lt;!&ndash;                :disabled="!(roles.admin || permission.account_edit)"&ndash;&gt;-->
          <!--                <el-option-->
          <!--                  v-for="(item, index) in statusList"-->
          <!--                  :key="index"-->
          <!--                  :value="item.value"-->
          <!--                  :label="item.label"-->
          <!--                >-->
          <!--                </el-option>-->
          <!--              </el-select>-->
          <!--            </div>-->
        </template>
      </avue-crud>

      <el-drawer
        size="50%"
        :title="drawerTitle"
        :visible.sync="visible"
        :modal-append-to-body="false"
        style="width: 100%"
        :close-on-click-modal="false"
        :before-close="handlerDrawerClose"
        :append-to-body="true"
      >
        <el-form
          ref="editForm"
          :model="form"
          label-width="100px"
          style="width: 90%; margin: 0 auto"
          :rules="optionRules()"
          :validate-on-rule-change="false"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="pullStatus">
                <el-select
                  :disabled="drawerTitle === '查 看'"
                  size="mini"
                  style="width: 100%"
                  v-model="form['status']"
                  filterable
                >
                  <el-option
                    v-for="item in this.statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-for="(item, index) in option.column"
              :key="index"
              v-if="
                  drawerTitle === '查 看'
                    ? item.viewDisplay === false
                      ? false
                      : true
                    : item.editDisplay === false
                    ? false
                    : true
                "
            >
              <el-form-item :label="item.label" :prop="item.prop">
                <el-select
                  v-if="item.prop=== 'offerId'"
                  :disabled="
                      drawerTitle === '查 看' ||
                      (item.prop === 'timezoneOffset' &&
                        form['platform'] !== 'kwai')
                    "
                  style="width: 100%"
                  size="mini"
                  v-model="form[item.prop]"
                  placeholder="请选择订单"
                  clearable
                  filterable
                  @change="item.changeMethod && item.changeMethod($event)"
                  :filter-method="costomFilterMethod"
                  @visible-change="clearOfferSelect"
                >
                  <el-option
                    v-for="item in filterOfferList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-select
                  clearable
                  :disabled="
                      drawerTitle === '查 看' ||
                      (item.prop === 'timezoneOffset' &&
                        form['platform'] !== 'kwai')
                    "
                  style="width: 100%"
                  size="mini"
                  v-else-if="item.type === 'select'"
                  v-model="form[item.prop]"
                  filterable
                  @change="item.changeMethod && item.changeMethod($event)"
                >
                  <el-option
                    v-for="it in item.dicData"
                    :key="item.props ? it[item.props.value] : it.value"
                    :label="item.props ? it[item.props.label] : it.label"
                    :value="item.props ? it[item.props.value] : it.value"
                  ></el-option>
                </el-select>
                <el-input
                  :disabled="drawerTitle === '查 看'"
                  v-else
                  size="mini"
                  v-model="form[item.prop]"
                  :readonly="item.readonly"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <div
            v-if="drawerTitle === '编 辑'"
            style="display: flex; justify-content: flex-end"
          >
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-circle-check"
              @click="rowUpdate"
              :loading="loading"
            >保存
            </el-button>
            <el-button
              size="mini"
              icon="el-icon-circle-close"
              @click="handlerDrawerClose"
            >取消
            </el-button
            >
          </div>
        </el-form>
        <div style="margin-left: 20px" v-show="drawerTitle === '查 看'">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="信息变更记录" name="1">
              <el-table :data="updateData" align="center" style="width: 100%">
                <el-table-column
                  prop="changeTypeName"
                  label="变更项"
                  width="120"
                >
                </el-table-column>
                <el-table-column prop="changelog" label="变更内容">
                </el-table-column>
                <el-table-column
                  prop="updateUserName"
                  label="操作人"
                  width="120"
                >
                </el-table-column>
                <el-table-column prop="createTime" label="变更时间" width="160">
                </el-table-column>
              </el-table>
              <div
                style="display: flex; justify-content: center; margin-top: 20px"
              >
                <el-pagination
                  background
                  @size-change="handleInfoSizeChange"
                  @current-change="handleInfoCurrentChange"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="updateInfoPage.size"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="updateInfoTotal"
                >
                </el-pagination>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-drawer>

      <account-add
        v-if="accountAddVisible"
        :visible="accountAddVisible"
        ref="accountAdd"
        @close="handleAddClose"
        @submit="handleAddSubmit"
        :account="account"
        :adv-add-platform="advPlatform"
        :user-list="addUserList"
        :offer-list="addOfferList"
      >
      </account-add>
      <account-add-fb
        v-if="facebookAccountVisible"
        :account="account"
        v-model="facebookAccountVisible"
        ref="accountAddFbRef"
        :adv-add-platform="advPlatform"
        :user-list="addUserList"
        :offer-list="addOfferList"
        @submit="handleSubmitAddFacebookAccounts"
      ></account-add-fb>
    </basic-container>
    <el-dialog
      :visible="batchUpdateTimezoneShow"
      @close="closeUpdateTimezone"
      :append-to-body="false"
      :modal-append-to-body="false"
    >
      <div>
        <i class="el-icon-warning" style="color: #cf9236"
        >注:更改的时区会在次日生效</i
        >
      </div>
      <div style="margin: 5px">
        <el-form v-model="batchSubmitForm">
          <el-form-item>
            <el-select v-model="batchSubmitForm.batchTimeZone" filterable>
              <el-option
                v-for="item in UTCList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin: 5px">
        <el-table :data="batchTimeZoneData">
          <el-table-column prop="name" label="账户名"/>
          <el-table-column prop="offerName" label="订单名"/>
        </el-table>
      </div>
      <div style="text-align: center; margin: 15px">
        <el-button type="primary" @click="batchChangeTimezone">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="批量修改状态"
      width="350px"
      :visible="batchUpdateStatusShow"
      @close="closeUpdateStatus"
      :append-to-body="false"
      :modal-append-to-body="false"
    >
      <div style="margin: 5px">
        <el-form v-model="batchUpdateStatusForm">
          <el-form-item label="状态更新为：">
            <el-select
              style="width: 250px"
              v-model="batchUpdateStatusForm.batchStatus"
              filterable
            >
              <el-option
                v-for="item in this.statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center">
        <el-button type="primary" @click="saveBatchUpdateStatus"
        >保存
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import store from "@/store";
import Moment from "moment";
import _ from "lodash";
import {
  getList,
  getSimpleList,
  getDetail,
  add,
  update,
  remove,
  getPlatformByOffer,
  changeOperator,
  comparePlatformAccount,
  batchUpateTimezone,
  accountUpdateInformation,
  changeStatus,
  exportOrders,
} from "@/api/business/account";
import {findObjectList} from "@/util/util";
import {
  getOfferList,
  getDetail as getOfferDetail,
} from "@/api/business/offer";
import {getAllUser} from "@/api/user";
import {getUrlData, getSysDictList} from "@/api/system/dict";
import beetlesTable from "@/components/basic-components/beetles-table";
import beetlesSearch from "@/components/beetles/beetles-search";
import accountAdd from "@/views/business/accountAdd";
import facebookLogin from "@/components/facebook-login/FacebookLogin";
import googleLogin from "@/components/google-login/GoogleLogin";
import func from "@/util/func";
import accountAddFb from "@/views/business/accountAddFb";
import {thousandSeparator} from "@/util/util";
import {platformLogo} from "../../util/beetles";

export default {
  components: {
    beetlesTable,
    beetlesSearch,
    accountAdd,
    facebookLogin,
    googleLogin,
    accountAddFb,
  },
  data() {
    // let checkPlatformId = (rule, value, callback) => {
    //   return this.checkPlatformId(rule, value, callback);
    // };
    return {
      UTCList: [
        {label: "UTC+0", value: 0},
        {label: "UTC-3", value: -3},
        {label: "UTC-5", value: -5},
        {label: "UTC-6", value: -6},
        {label: "UTC+5", value: 5},
        {label: "UTC+7", value: 7},
        {label: "UTC+8", value: 8},
      ],
      statusList: [
        {label: "开启", value: 0},
        {label: "暂停", value: 1},
        {label: "关闭", value: 2},
      ],
      batchSubmitForm: {
        batchTimeZone: 0,
      },
      batchUpdateStatusForm: {
        batchStatus: 0,
      },
      batchTimeZoneData: [],
      batchUpdateTimezoneShow: false,
      batchUpdateStatusShow: false,
      accountNameStyle: "",
      defaultStyle: "color:black",
      showOfferName: false,
      sortList: [],
      accountAddVisible: false,
      facebookParams: {
        loading: false,
        appId: "927869380715412", //正式
        // appId: '689751319015544',//测试
        version: "v14.0",
        isConnected: false,
        loginOptions: {
          scope: "email,ads_read,ads_management,business_management",
        },
      },
      googleParams: {
        enable: false,
        isLogin: false,
        client_id:
          "434175254256-f9ldue13rpgn7c6oa5n6s6qqsr5geoge.apps.googleusercontent.com",
        developerToken: "kiPrjMIOCshi2m-2gfpnpQ",
        scope: "https://www.googleapis.com/auth/adwords",
      },
      account: {},
      upIcon: "el-icon-arrow-down",
      searchIcon: "el-icon-search",
      emptyIcon: "el-icon-delete",
      searchConceal: false,
      validateCheckMode: "add",
      drawerTitle: "",
      activeNames: ["1"],
      updateData: [],
      currentRow: {},
      updateInfoPage: {
        current: 1,
        size: 10,
      },
      updateInfoTotal: 0,
      addForm: {
        visible: false,
        loading: false,
        allAccountList: [],
        form: {
          offerId: null,
          platform: null,
          status: null,
          bindStatus: null,
          owner: null,
          operator: null,
          accountList: [],
        },
        rules: {
          offerId: [
            {required: true, message: "请选择订单名称", trigger: "change"},
          ],
          platform: [
            {required: true, message: "请选择媒体", trigger: "change"},
          ],
          status: [
            {required: true, message: "请选择状态", trigger: "change"},
          ],
          bindStatus: [
            {required: true, message: "请选择绑定状态", trigger: "change"},
          ],
          operator: [
            {required: true, message: "请选择运营人", trigger: "change"},
          ],
          // owner: [{required: true, message: "请选择所有人", trigger: "change"}],
        },
      },
      form: {
        offerName: null,
        name: null,
        platformId: null,
        customerName: null,
        agencyName: null,
        platform: null,
        type: null,
        status: null,
        owner: null,
        operator: null,
        binder: null,
        accountList: [],
      },
      queryForm: {
        offerName: null,
        offerId: null,
        name: null,
        platformId: null,
        customerName: null,
        agencyName: null,
        platform: [],
        type: "1",
        status: null,
        bindStatus: null,
        bindTime: null,
        owner: null,
        operator: null,
        subStatus: null,
        enableTime: null,
        pauseTime: null,
        closeTime: null,
      },
      query: {
        type: "1",
      },
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      offerList: [],
      platformList: [],
      advPlatform: [], //广告
      userList: [], // 媒体列表
      platformLoading: false,
      visible: false,
      bindStatusList: [
        {label: "已绑定", value: 0},
        {label: "解绑", value: 1},
        {label: "被禁止", value: 2},
      ],
      typeList: [
        {label: "全部", value: "0"},
        {label: "内部", value: "1"},
        {label: "外部", value: "2"},
      ],
      systemStatusList: [
        {label: "待启用", value: 0},
        {label: "启用", value: 1},
        {label: "0消耗", value: 2},
        {label: "封号(待申诉)", value: 3},
        {label: "封号", value: 4},
      ],
      option: {
        //   excelBtn: true,
        stripe: true,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 120,
        addBtn: false,
        selection: true,
        dialogClickModal: false,
        dialogWidth: 1200,
        column: [
          {
            label: "类型",
            prop: "type",
            type: "select",
            hide: true,
            dicData: [
              {label: "全部", value: 0},
              {label: "内部", value: 1},
              {label: "外部", value: 2},
            ],
            slot: true,
            addDisplay: false,
            editDisplay: false,
            searchValue: "1",
            searchClearable: false,
            overHidden: true,
          },
          {
            width: 150,
            label: "账户名",
            prop: "name",
            rules: [
              {
                required: true,
                message: "请输入名称",
                trigger: "blur",
              },
            ],
            overHidden: true,
            addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
          },
          {
            label: "账户ID",
            prop: "platformId",
            rules: [
              {
                required: true,
                validator: this.checkPlatformId,
                trigger: "change",
              },
            ],
            overHidden: true,
            addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
          },
          {
            label: "时区",
            prop: "timezoneOffset",
            dictData: [],
            type: "select",
          },
          {
            label: "代理",
            prop: "agencyName",
            type: "select",
            dicData: [],
          },
          {
            label: "订单名",
            prop: "offerId",
            hide: true,
            type: "select",
            viewDisplay: false,
            dicData: [],
            props: {
              label: "name",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请输选择订单名称",
                trigger: "change",
              },
            ],
            formsolt: true,
            filterable: true,
            overHidden: true,
            changeMethod: async (val) => {
              const {data: res} = await getOfferDetail(val);
              // console.log(res)
              this.form.customerName = res.data.customerName;
            },
          },
          {
            label: "媒体",
            prop: "platform",
            type: "select",
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择投放媒体",
                trigger: "change",
              },
            ],
            formsolt: true,
            overHidden: true,
          },
          //this.findObject(this.option.column, "parentId");
          {
            label: "绑定状态",
            prop: "bindStatus",
            type: "select",
            hide: true,
            dicData: [
              {label: "已绑定", value: 0},
              {label: "解绑", value: 1},
              {label: "被禁止", value: 2},
            ],
            rules: [
              {
                required: true,
                message: "请选择绑定状态",
                trigger: "change",
              },
            ],
          },
          {
            label: "订单名",
            prop: "offerName",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
          {
            label: "客户",
            prop: "customerName",
            addDisplay: false,
            viewDisplay: store.getters.userInfo.is_agency === 1,
            editDisplay: store.getters.userInfo.is_agency === 1,
            editDisabled: true,
            hide: store.getters.userInfo.is_agency !== 1,
            overHidden: true,
            searchSize: "mini",
            readonly: true,
          },
          {
            editDisplay: false,
            viewDisplay: false,
            label: "状态",
            prop: "status",
            type: "select",
            dicData: this.statusList,
            searchSize: "mini",
            slot: true,
            width: 100,
          },
          {
            width: 90,
            label: "余额($)",
            prop: "limits",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            sortable: "custom",
          },
          {
            label: "运营人",
            prop: "operator",
            type: "select",
            dicData: [],
            props: {
              label: "realName",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择运营人",
                trigger: "change",
              },
            ],
            hide: true,
            viewDisplay: false,
            searchLabelWidth: 100,
            filterable: true,
            overHidden: true,
          },
          {
            label: "运营人",
            prop: "operatorName",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            slot: true,
          },
          {
            label: "绑定人",
            prop: "binder",
            type: "select",
            addDisplay: false,
            dicData: [],
            props: {
              label: "realName",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择绑定人",
                trigger: "change",
              },
            ],
            hide: true,
            viewDisplay: false,
            overHidden: true,
          },
          {
            label: "绑定人",
            prop: "binderName",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
          {
            label: "绑定日期",
            prop: "bindTime",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
          {
            label: "",
            prop: "accountList",
            type: "dynamic",
            span: 24,
            children: {
              align: "center",
              headerAlign: "center",
              type: "crud",
              column: [
                {
                  width: 200,
                  label: "账户名",
                  prop: "name",
                },
                {
                  width: 200,
                  label: "账户ID",
                  prop: "platformId",
                },
              ],
            },
            hide: true,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "系统状态",
            prop: "subStatus",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            slot: true,
            width: 120,
          },
          {
            label: "启用日期",
            prop: "enableTime",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
          {
            label: "0消耗日期",
            prop: "pauseTime",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
          {
            label: "封号日期",
            prop: "closeTime",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
        ],
      },
      data: [],
      currOpRowId: "",
      innerUserList: [],
      operatorId: [],
      allUserList: [],
      addPlatformList: [],
      addOfferList: [],
      addUserList: [],
      facebookAccountVisible: false,
      // 代理
      agencyNameList: [],
      // 订单名称筛选值
      offerFilterVal: ''
    };
  },
  computed: {
    ...mapGetters(["permission", "userInfo", "roles"]),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    filterOfferList() {
      if (this.offerFilterVal === '') {
        return this.offerList
      } else {
        return this.offerList.filter(offer => {
          const input = this.offerFilterVal.toLowerCase()
          const lable = offer.name.toLowerCase()
          return offer.id.includes(this.offerFilterVal) || lable.includes(input)
        })
      }

    }
  },
  created() {
    // this.buildUTCList()
    const that = this
    this.$bus.on('getAccount', function (val) {
      that.queryForm.name = val
      that.searchForm()
    })
    try {
      if (this.$route.query.data !== undefined) {
        this.queryForm.platformId = this.$route.query.data.join(",");
        this.searchForm();
        this.accountNameStyle = "color:red";
        this.showOfferName = true;
      }
    } catch (e) {
      console.log(e)
    }
    // window.addEventListener('keyup',this.searchForm) //监听键盘事件
    getSysDictList("platforms").then((map) => {
      this.advPlatform = map["platforms"];
      findObjectList(this.option.column, "platform", "prop")[0].dicData =
        map["platforms"];
    });
    getAllUser({statusList: "0,1,2", isAll: true}).then((res) => {
      this.allUserList = res.data.data;
    });
    getUrlData("/api/beetles-business/offer/get-select").then((res) => {
      findObjectList(this.option.column, "offerId", "prop")[0].dicData =
        res.data.data;
      this.addOfferList = res.data.data;
    });
    getUrlData("/api/blade-user/select/user").then((res) => {
      findObjectList(this.option.column, "operator", "prop")[0].dicData =
        res.data.data;
      // findObjectList(this.option.column, 'owner', 'prop')[0].dicData = res.data.data;
      findObjectList(this.option.column, "binder", "prop")[0].dicData =
        res.data.data;
      this.addUserList = res.data.data;
    });
    getSimpleList({}).then((res) => {
      this.addForm.allAccountList = res.data.data;
    });
    findObjectList(this.option.column, "timezoneOffset", "prop")[0].dicData =
      this.UTCList;
    this.getAgencyNameList();
  },
  mounted() {
    this.getOfferList();
    getAllUser().then((res) => {
      this.innerUserList = res.data.data;
    });
  },
  methods: {
    //导出excal订单
    handleExport() {
      this.$confirm("是否导出账户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let page = this.page;
        let params = {};
        params.sortList = JSON.stringify(this.sortList);
        exportOrders(
          page.currentPage,
          page.pageSize,
          Object.assign({}, params, this.query)
        ).then((res) => {
          var blob = new Blob([res.data], {
            type: "application/octet-stream;charset=UTF-8",
          });
          var contentDisposition = res.headers["content-disposition"];
          var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
          var result = patt.exec(contentDisposition);
          var filename = result[1];
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); // 创建下载的链接
          var reg = /^["](.*)["]$/g;
          downloadElement.style.display = "none";
          downloadElement.href = href;
          downloadElement.download = decodeURI(filename.replace(reg, "$1")); // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href);
        });
      });
    },

    async changeStatus(val, row) {
      let stop = false;
      if (val != 0) {
        await this.$confirm(
          "此操作将会导致该账户停止拉取数据, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).catch(() => {
          stop = true;
        });
      }
      if (stop) return this.refreshChange();
      const res = await changeStatus(row.id, val);
      if (res.data.code === 200) {
        this.$message({
          type: "success",
          message: "状态修改成功!",
        });
      }
      this.refreshChange();
    },
    async saveBatchUpdateStatus() {
      let stop = false;
      if (this.batchUpdateStatusForm.batchStatus != 0) {
        await this.$confirm(
          "此操作将会导致这些账户停止拉取数据, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).catch(() => {
          stop = true;
        });
      }
      this.batchUpdateStatusShow = false;
      if (stop) {
        return;
      }
      let ids = [];
      this.selectionList.map((item) => {
        ids.push(item.id);
      });
      const res = await changeStatus(
        ids.join(","),
        this.batchUpdateStatusForm.batchStatus
      );
      if (res.data.code === 200) {
        this.$message({
          type: "success",
          message: "账户重启成功!",
        });
      }
      this.refreshChange();
    },
    batchChangeTimezone() {
      let idsArr = this.batchTimeZoneData.map((item) => {
        return item.id;
      });
      let ids = idsArr.join(",");
      let timezone = this.batchSubmitForm.batchTimeZone;
      let param = {
        ids: ids,
        timezone: timezone,
      };
      batchUpateTimezone(param).then((res) => {
        this.$message.success("批量修改时区成功");
      });
      this.closeUpdateTimezone();
    },
    buildUTCList() {
      for (let i = 1; i < 13; i++) {
        let optP = {
          label: "UTC+" + i + ":00",
          value: i,
        };
        this.UTCList.push(optP);
      }
      let zero = {
        label: "UTC0:00",
        value: 0,
      };
      this.UTCList.push(zero);
      for (let i = 1; i < 13; i++) {
        let optN = {
          label: "UTC-" + i + ":00",
          value: -i,
        };
        this.UTCList.push(optN);
      }
      let u13 = {
        label: "UTC+13:00",
        value: 13,
      };
      let u14 = {
        label: "UTC+14:00",
        value: 14,
      };
      this.UTCList.push(u13);
      this.UTCList.push(u14);
    },
    closeUpdateStatus() {
      this.batchUpdateStatusShow = false;
    },
    closeUpdateTimezone() {
      this.batchUpdateTimezoneShow = false;
      this.batchTimeZoneData = [];
    },
    batchUpdateStatus() {
      if (this.selectionList.length < 1) {
        this.$message.warning("至少要选择一个账户");
        return;
      }
      // this.batchUpdateStatusShow = true;
      this.saveBatchUpdateStatus()
    },
    /**
     * 批量更改时区
     */
    batchUpdateTimezone() {
      if (this.selectionList.length < 1) {
        this.$message.warning("至少要选择一个账户");
      } else {
        let arr = _.cloneDeep(this.selectionList);
        let arrWithoutKwai = arr.filter((item) => item.platform !== "kwai");
        if (arrWithoutKwai.length > 0) {
          this.$message.warning("只支持修改kwai账户时区");
          return;
        }
        if (arr.length === 0) {
          this.$message.warning("至少要选择一个kwai账户");
          return;
        }
        this.batchUpdateTimezoneShow = true;
        this.batchTimeZoneData = arr;
      }
    },
    /**
     * 获取 option中定义的rules
     */
    optionRules() {
      let rules = {};
      this.option.column.map((item) => {
        if (item.rules) {
          let rule = {[item.prop]: item.rules};
          rules = Object.assign(rules, rule);
        }
      });
      return rules;
    },
    /**
     * 关闭查看/编辑弹窗
     */
    handlerDrawerClose() {
      this.visible = false;
      // this.form = {}
      // this.$nextTick(() => {
      if (this.$refs["editForm"] != null) {
        this.$refs["editForm"].clearValidate();
      }
      // });
    },
    unfoldIcon() {
      if (this.upIcon === "el-icon-arrow-down") {
        this.upIcon = "el-icon-arrow-up";
        this.searchConceal = true;
      } else {
        this.upIcon = "el-icon-arrow-down";
        this.searchConceal = false;
      }
    },
    findObjectList(dic, value, propName = "value") {
      return findObjectList(dic, value, propName);
    },
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.accountPlatform.blur();
      if (!isShowSelectOptions) this.$refs.accountStatus.blur();
      if (!isShowSelectOptions) this.$refs.accountType.blur();
    },
    buildSearch() {
      let query = {...this.queryForm};
      console.log(this.queryForm);
      query.platform = this.queryForm.platform.join(",");
      delete query.bindTime;
      delete query.enableTime;
      delete query.pauseTime;
      delete query.closeTime;
      if (
        this.queryForm.bindTime != null &&
        this.queryForm.bindTime.length == 2
      ) {
        let bindTimeList =
          Moment(this.queryForm.bindTime[0]).format("YYYY-MM-DD") +
          "," +
          Moment(this.queryForm.bindTime[1]).format("YYYY-MM-DD");
        this.$set(query, "bindTimeList", bindTimeList);
      }
      if (
        this.queryForm.enableTime != null &&
        this.queryForm.enableTime.length == 2
      ) {
        let enableTimeList =
          Moment(this.queryForm.enableTime[0]).format("YYYY-MM-DD") +
          "," +
          Moment(this.queryForm.enableTime[1]).format("YYYY-MM-DD");
        this.$set(query, "enableTimeList", enableTimeList);
      }
      if (
        this.queryForm.pauseTime != null &&
        this.queryForm.pauseTime.length == 2
      ) {
        let pauseTimeList =
          Moment(this.queryForm.pauseTime[0]).format("YYYY-MM-DD") +
          "," +
          Moment(this.queryForm.pauseTime[1]).format("YYYY-MM-DD");
        this.$set(query, "pauseTimeList", pauseTimeList);
      }
      if (
        this.queryForm.closeTime != null &&
        this.queryForm.closeTime.length == 2
      ) {
        let closeTimeList =
          Moment(this.queryForm.closeTime[0]).format("YYYY-MM-DD") +
          "," +
          Moment(this.queryForm.closeTime[1]).format("YYYY-MM-DD");
        this.$set(query, "closeTimeList", closeTimeList);
      }
      if (query.agencyName) {
        query.agencyName = query.agencyName.join(',')
      }
      this.query = query;
    },
    // 搜索按钮函数
    searchForm() {
      this.buildSearch();
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //清空按钮函数
    emptyForm() {
      this.queryForm = {
        offerName: null,
        name: null,
        platformId: null,
        customerName: null,
        platform: null,
        type: null,
        status: null,
        bindStatus: null,
        bindTime: null,
        owner: null,
        operator: null,
      };
      this.searchForm();
    },
    handleChangeOperator(id, index) {
      changeOperator(id, index).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!",
        });
      });
    },
    permissionList(key, row) {
      if (key === "addBtn") {
        if (this.roles.admin || this.roles.operator || this.roles.optimizer) {
          return true;
        } else {
          return false;
        }
      } else if (key === "delBtn") {
        if (
          (this.roles.admin || this.roles.operator || this.roles.optimizer) &&
          row.hasDelPem
        ) {
          return true;
        } else {
          return false;
        }
      } else if (key === "editBtn") {
        if (this.roles.admin || this.roles.operator || this.roles.optimizer) {
          if (row.originTenantId !== "") {
            return false;
          } else {
            return true;
          }
        } else {
          return false;
        }
      }
      return true;
    },
    handleAddClose() {
      this.addForm.visible = false;
      this.accountAddVisible = false;
    },
    handleAddSubmit() {
      this.addForm.visible = false;
      this.accountAddVisible = false;
      this.refreshChange();
    },
    appendAccount(row) {
      if (row.accountList == null) {
        row.accountList = [];
      }
      row.accountList.push({name: "", platformId: ""});
    },
    deductAccount(row, idx) {
      row.accountList.splice(idx, 1);
    },
    handleAddSave() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.addForm.loading = true;
          this.addForm.form.accountList.forEach((a) => {
            a.platformId = a.platformId.trim();
          });
          add(this.addForm.form).then(
            () => {
              this.addForm.loading = false;
              this.addForm.visible = false;
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              this.addForm.loading = false;
              this.addForm.visible = false;
              window.console.log(error);
            }
          );
        }
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.form.platformId = this.form.platformId.trim();
          let params = {};
          Object.assign(params, this.form);
          params.limits = undefined;
          update(params).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.loading = false;
              this.handlerDrawerClose();
            },
            (error) => {
              this.loading = false;
            }
          );
        }
      });
    },
    rowView(row) {
      this.beforeOpen("check", row);
      this.drawerTitle = "查 看";
      this.validateCheckMode = "check";
      this.visible = true;
      this.currentRow = row;
      // console.log(row.id)
      // accountUpdateInformation(row.id, this.updateInfoPage).then(res => {
      //   this.updateData = res.data.data
      // })
      this.getUpdateData();
    },
    async getUpdateData() {
      const {data: res} = await accountUpdateInformation(
        this.currentRow.platformId,
        this.updateInfoPage
      );
      this.updateData = res.data.records;
      this.updateInfoTotal = res.data.total;
    },
    rowEdit(row) {
      this.beforeOpen("edit", row);
      this.drawerTitle = "编 辑";
      this.validateCheckMode = "edit";
      this.visible = true;
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleAdd() {
      this.addForm.form = {
        offerId: null,
        platform: null,
        status: null,
        bindStatus: null,
        owner: null,
        operator: null,
        accountList: [{}],
      };
      this.validateCheckMode = "add";
      this.addForm.visible = true;
      let self = this;
      this.$nextTick(() => {
        if (self.$refs["addForm"] != null) {
          self.$refs["addForm"].clearValidate();
        }
      });
    },

    handleAddNew() {
      // let accounts = [];
      // for (let i = 0; i < 2; i++) {
      //   accounts.push({
      //     name: "namenamename" + i,
      //     platformId: 10000000 + i,
      //   })
      // }
      // this.account = {accounts: accounts, platform: 'facebook'}
      // this.facebookAccountVisible = true;
      this.accountAddVisible = true;
      // this.$nextTick(()=>{
      //   this.$refs.accountAdd.add();
      // })
    },

    checkPlatformId(rule, value, callback) {
      if (value != null) value = value.trim();
      if (value == null || value == "") {
        return callback(new Error("请输入媒体账户ID"));
      } else {
        let accountRegex = /^[\d]+(-[\d]+)*$/;
        let errMsg = "输入的账户ID格式不正确，请查验后输入。";
        if (this.validateCheckMode == "edit") {
          if (this.form.platform != null && this.form.platform != "") {
            if (this.form.platform.toLowerCase() == "google") {
              accountRegex = /^[\d]{3}-[\d]{3}-[\d]{4}$/;
            } else {
              accountRegex = /^[\d]+$/;
            }
          }
        }
        if (this.validateCheckMode == "add") {
          if (
            this.addForm.form.platform != null &&
            this.addForm.form.platform != ""
          ) {
            if (this.addForm.form.platform.toLowerCase() == "google") {
              accountRegex = /^[\d]{3}-[\d]{3}-[\d]{4}$/;
            } else {
              accountRegex = /^[\d]+$/;
            }
          }
        }
        if (!accountRegex.test(value)) {
          return callback(new Error(errMsg));
        }
        if (this.validateCheckMode == "edit") {
          if (this.form.oldPlatformId != value) {
            if (
              findObjectList(this.addForm.allAccountList, value, "platformId")
                .length > 0
            ) {
              return callback(new Error("账户ID已存在，请重新输入账户ID"));
            }
          }
        }
        if (this.validateCheckMode == "add") {
          if (
            findObjectList(this.addForm.allAccountList, value, "platformId")
              .length > 0
          ) {
            return callback(new Error("账户ID已存在，请重新输入账户ID"));
          }
        }
        if (
          findObjectList(this.addForm.form.accountList, value, "platformId")
            .length > 1
        ) {
          return callback(new Error("账户ID重复，请重新输入账户ID"));
        }
        callback();
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      let back = false;
      this.selectionList.map((item) => {
        if (!item.hasDelPem) {
          this.$message.warning("分享的账户不可删除！");
          back = true;
        }
      });
      if (back) return;
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(type, row) {
      if (type == "edit") {
        this.validateCheckMode = "edit";
      }
      this.currOpRowId = row.id;
      console.log("row", row);
      if (row.offerId === -1) {
        this.platformList = [{label: "Tiktok", value: "tiktok"}];
      } else {
        getPlatformByOffer(row.offerId).then((res) => {
          this.platformList = res.data.data;
        });
      }

      getDetail(this.currOpRowId).then((res) => {
        this.form = res.data.data;
        if (row.offerId === -1) {
          this.form.offerId = "";
          this.form.bindStatus = "";
        }
        this.form.oldPlatformId =
          this.form.platformId != null ? this.form.platformId.trim() : null;
      });
    },
    searchReset() {
      this.emptyForm();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    queryPlatformByOffer(row) {
      this.platformLoading = true;
      row.platform = [];
      getPlatformByOffer(row.offerId).then((res) => {
        this.platformList = res.data.data;
        this.platformLoading = false;
      });
    },
    queryAddPlatformByOffer(offerId) {
      if (offerId == "") {
        this.addPlatformList = [];
        this.addForm.form.platform = "";
      } else {
        getPlatformByOffer(offerId).then((res) => {
          this.addPlatformList = res.data.data;
          if (this.addForm.form.platform != "") {
            if (
              findObjectList(
                this.addPlatformList,
                this.addForm.form.platform,
                "value"
              ).length == 0
            ) {
              this.addForm.form.platform = "";
            }
          }
        });
      }
    },
    getOfferList() {
      getOfferList().then((res) => {
        this.offerList = res.data.data;
      });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.sortList = JSON.stringify(this.sortList);
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign({}, params, this.query)
      ).then((res) => {
        const data = res.data.data;
        data.records.map((row, index) => {
          this.operatorId[index] = row.operator;
        });
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    getRowClass({row}) {
      if (row.subStatus == 3) {
        return "row-color";
      }
    },
    //facebook sdk 加载
    sdkLoaded(payload) {
      console.log(payload);
      this.facebookParams.isConnected = payload.isConnected;
      // if (this.isConnected) this.getFbAccounts()
    },
    onLogin(resp) {
      console.log(resp);
      if (resp && resp.isConnected) {
        this.facebookParams.isConnected = true;
      }
    },
    onLogout(resp) {
      if (resp && !resp.isConnected) {
        this.facebookParams.isConnected = false;
      }
    },
    //获取FB用户信息数据
    getFbAccounts() {
      let that = this;
      this.loading = true;
      this.$refs.facebook.getAdsAccount().then((res) => {
        if (res.data && res.data.length > 0) {
          let accounts = [];
          res.data.map((item) => {
            accounts.push({
              name: item.name,
              platformId: item.account_id,
              accountStatus: item.account_status,
            });
          });
          let account = {accounts: accounts, platform: "facebook"};
          comparePlatformAccount(account).then((res) => {
            this.loading = false;
            let newAccounts = [];
            res.data.data.newAccounts.map((item) => {
              newAccounts.push({
                name: item.name,
                platformId: item.platformId,
              });
            });
            if (newAccounts.length > 0) {
              that.account = {accounts: newAccounts, platform: "facebook"};
              this.facebookAccountVisible = true;
            } else {
              that.$message({
                type: "warning",
                message: "没有可导入的 Facebook 账户!",
              });
            }
          });
        } else {
          this.loading = false;
          if (res.error) {
            that.$message({
              type: "error",
              message: res.error,
            });
          } else {
            that.$message({
              type: "warning",
              message: "没有可导入的 Facebook 账户!",
            });
          }
        }
      });
    },
    googleChangeStatus({isLogin, user}) {
      this.googleParams.isLogin = isLogin;
    },
    getGoogleAccounts(response) {
      // const loading = this.$loading({
      //   lock: true,
      //   text: '正在获取 Google 账户，请稍等',
      //   spinner: "el-icon-loading"
      // });
      //   {"resourceNames": ["customers/9513454282"]}
      this.loading = true;
      this.$refs.google
        .getAdsAccount()
        .then((response) => {
          this.loading = false;
          console.log("onCurrentUser", response);
          let resourceNames = response.resourceNames;
          let accounts = [];
          for (let i = 0; i < resourceNames.length; i++) {
            let account = resourceNames[i].split("/");
            accounts.push({
              name: account[0],
              platformId: func.googleAccountFormat(account[1]),
            });
          }
          let account = {accounts: accounts, platform: "google"};
          comparePlatformAccount(account).then((res) => {
            loading.close();
            let newAccounts = [];
            res.data.data.newAccounts.map((item) => {
              newAccounts.push({
                name: item.name,
                platformId: item.platformId,
              });
            });
            if (newAccounts.length > 0) {
              this.account = {accounts: newAccounts, platform: "google"};
              this.accountAddVisible = true;
            } else {
              this.$message({
                type: "warning",
                message: "没有可导入的 Google 账户!",
              });
            }
          });
        })
        .catch((err) => {
          // loading.close();
          this.$message({
            type: "error",
            message: "获取失败：" + err.message,
          });
        });
    },
    // by marco
    // 处理提交表单后刷新页面
    handleSubmitAddFacebookAccounts() {
      this.facebookAccountVisible = false;
      this.refreshChange();
    },
    thousandSeparator(row) {
      let num = row.limits;
      if (num == null) {
        return "/";
      }
      return thousandSeparator(num);
    },
    // 排序方法
    handleSortChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = "desc";
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = "asc";
        //不排序
      }
      if (orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //媒体 logo
    platformLogo(platform) {
      return platformLogo(platform);
    },
    async getAgencyNameList() {
      const {agency_list} = await getSysDictList("agency_list");
      this.agencyNameList = agency_list.map((item) => {
        return {
          label: item.dictValue,
          value: item.dictValue,
        };
      });
      const agencyName = this.option.column.find(
        (item) => item.prop === "agencyName"
      );
      agencyName.dicData = this.agencyNameList;
    },
    handleInfoSizeChange(val) {
      this.updateInfoPage.size = val;
      this.updateInfoPage.current = 1;
      this.getUpdateData();
    },
    handleInfoCurrentChange(val) {
      this.updateInfoPage.current = val;
      this.getUpdateData();
    },
    //自定义筛选方法
    costomFilterMethod(val) {
      this.offerFilterVal = val
    },
    clearOfferSelect(val) {
      if (!val) {
        this.offerFilterVal = ''
      }
    }
  },
};
</script>
<style>
.hanDer {
  overflow: hidden;
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.text {
  width: 45px;
  height: 30px;
  float: left;
  font-size: 13px;
  margin-top: 3px;
  color: #72767b;
}

.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}

.button {
  margin: auto;
  background-color: #1e9fff;
}

.facebook-login {
  margin-left: 10px;
}

.google-login {
  margin-left: 10px;
}
</style>
<style lang="scss" scoped>
/deep/ .current-op-row {
  background-color: #f5dab1;
}

/deep/ .row-color {
  color: red;
}

.beetles_table_left {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.text-link {
  text-decoration: underline;
}

.popover_pane {
  display: flex;
  flex-direction: column;

  div {
    margin-left: 5px;
  }

  span {
    margin-left: 10px;
    font-size: 14px;
  }
}

///deep/ .facebook-login button {
//  min-width: 100px;
//  border-radius: 3px;
//  line-height: 32px;
//  font-size: 12px;
//}
///deep/ .facebook-login img {
//  //display: none;
//}
</style>
